package com.yami.shop.seckill.comment.listener;

import cn.binarywang.wx.miniapp.bean.live.WxMaLiveResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.event.ProcessSeckillProdPriceEvent;
import com.yami.shop.bean.event.SubmitSeckillOrderEvent;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.Product;
import com.yami.shop.seckill.comment.model.Seckill;
import com.yami.shop.seckill.comment.model.SeckillOrder;
import com.yami.shop.seckill.comment.service.SeckillOrderService;
import com.yami.shop.seckill.comment.service.SeckillService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 处理活动商品价格的事件
 * @author lhd
 */
@Component("processSeckillProdPriceListener")
@AllArgsConstructor
public class ProcessSeckillProdPriceListener {

    private final SeckillService seckillService;

    @EventListener(ProcessSeckillProdPriceEvent.class)
    public void processSeckillProdPrice(ProcessSeckillProdPriceEvent event) {
        List<Product> products = event.getProducts();
        List<Long> prodIds = new ArrayList<>();
        products.forEach(product -> prodIds.add(product.getProdId()));
        Date date = new Date();
        List<Seckill> seckillList = seckillService.list(new LambdaQueryWrapper<Seckill>()
                .eq(Seckill::getStatus, 1).lt(Seckill::getStartTime, date)
                .gt(Seckill::getEndTime, date).in(Seckill::getProdId, prodIds));
        Map<Long, Double> priceMap = seckillList.stream().collect(Collectors.toMap(Seckill::getProdId, Seckill::getSeckillPrice));
        for (Product product : products) {
            Double price = priceMap.get(product.getProdId());
            product.setPrice(price);
        }
    }

}
